import axios from 'axios';
import { getToken } from './auth'
import { Message } from 'element-ui';
import { baseURL } from './baseConfig';
import Store from '../store'

var instance = axios.create({
  headers: {
    'Content-Type': 'application/json',
  },
});

instance.defaults.timeout = 10000;
instance.defaults.baseURL = baseURL;
instance.defaults.isCustomHeaders = true; // 是否拦截器重置请求头
instance.interceptors.request.use(
  async (config) => {
    if (config.isCustomHeaders) {
      config.headers = {
        ...config.headers,
      };
    }
    if (getToken()) {
      config.headers['token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  },
);

// 中间件 拦截请求-
instance.interceptors.response.use(
  (response) => {
    return response;
  },
  (err) => {
    Message.error('服务端错误，请稍后重试！');
    return Promise.reject(err);
  },
);

const exceptionHandling = (data) => {
  if (data?.status === 200) {
    return data;
  }
  Message.error('服务发生错误');
  return false;
};

const safeRequest = (url, options) => {
  return new Promise((resolve, reject) => {
    instance({
      ...options,
      params: options.params,
      data: options.data,
      url,
      headers: {
        ...options?.header,
      },
    }).then(
      (response) => {
        const res = exceptionHandling(response);
        if (res) {
          if(res.config.url === '/project/common/file/upload') {
            resolve(res.data);
            return;
          }
          if(options?.responseType === 'blob') {
            resolve(res);
            return;
          }
          if (res.data.success) {
            resolve(res.data.data);
          } else if (res.data.code === 401) {
            reject(res);
            Message.error(res.data.message);
            Store.dispatch('userLoginOut');
          } else {
            reject(res);
            Message.error(res.data.message);
          }
        }
      },
      (err) => {
        reject(err);
      },
    );
  });
};

/**
 * get
 * @param url
 * @param opts
 * @returns {Promise}
 */
const get = (url, opts = {}) => {
  return safeRequest(url, opts);
};

/**
 * post
 * @param url
 * @param opts
 * @returns {Promise}
 */
const post = (url, opts = {}) => {
  return safeRequest(url, {
    ...opts,
    method: 'POST',
  });
};

/**
 * put
 * @param url
 * @param opts
 * @returns {Promise}
 */
const put = (url, opts = {}) => {
  return safeRequest(url, {
    ...opts,
    method: 'PUT',
  });
};

/**
 * delete
 * @param url
 * @param opts
 * @returns {Promise}
 */
const reqDelete = (url, opts = {}) => {
  return safeRequest(url, {
    ...opts,
    method: 'DELETE',
  });
};

const jsonp = (url) => {
  return new Promise((resolve) => {
    // 这里的 "jsonCallBack" ，和调用的 jsonp 的 url 中的 callback 值相对应（见粗体字）

    window.jsonCallBack = (result) => {
      resolve(result);
    };

    const JSONP = document.createElement('script');

    JSONP.type = 'text/javascript';

    JSONP.src = url;

    document.getElementsByTagName('head')[0].appendChild(JSONP);

    setTimeout(() => {
      document.getElementsByTagName('head')[0].removeChild(JSONP);
    }, 500);
  });
};

export default {
  instance,
  get,
  post,
  put,
  reqDelete,
  jsonp,
};